<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !reportInfo.visible && !reportDetailInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="设备试用明细"
        :needOperateAffair="false"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canRevoke" @click="handelMethodRequest('revoke')"
            >撤回
          </el-button>
          <el-button
            v-if="canCancelAudit"
            @click="handelMethodRequest('cancelAudit')"
            >销审
          </el-button>
          <el-button v-if="canCheck" @click="handelMethodRequest('check')"
            >批准
          </el-button>
          <el-button v-if="canSubmit" @click="handelMethodRequest('submit')"
            >提交
          </el-button>
          <el-button v-if="canRefuse" @click="handelMethodRequest('refuse')"
            >拒绝</el-button
          >
          <el-button v-if="canReject" @click="handelMethodRequest('reject')"
            >驳回</el-button
          >
          <el-button v-if="canCompleted" @click="completed"
            >试用完成</el-button
          >
          <el-button v-if="canReportDetails" @click="reportDetails"
            >报告详情</el-button
          >
          <el-button v-if="canRelatedAssets" @click="relatedAssets"
            >关联资产分类</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button> -->
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-supplierBalanceAmount>
                {{ infoList.data.supplierSumAmount - infoList.data.sumAmount }}
              </template>
              <template v-slot:basic-mainFileUrlList>
                <span v-if="infoList.data.mainFileUrlList">
                  <eleGallery
                    :lazy="true"
                    :size="150"
                    :source="infoList.data.mainFileUrlList"
                    title="附件"
                  ></eleGallery>
                </span>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <purch-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :tableKey="modifyInfo.tableKey"
      :id="modifyInfo.orderId"
      @returnModify="returnModify"
    />
    <report
      v-if="reportInfo.visible"
      v-model:visible="reportInfo.visible"
      :title="reportInfo.title"
      :id="reportInfo.orderId"
      @returnModify="returnModify"
    />
    <reportDetail
      v-if="reportDetailInfo.visible"
      v-model:visible="reportDetailInfo.visible"
      :id="reportDetailInfo.orderId"
      :invoiceType="reportDetailInfo.invoiceType"
      @returnBack="getList"
    />
    <SelectAssetClassify
      v-if="selectAssetClassifyInfo.visible"
      v-model:showDialog="selectAssetClassifyInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectAssetClassifyInfoCallBack"
    />
  </div>
</template>

<script setup name="deviceTrialManageDetail">
import {
  getTrialById,
  methodTrial,
  exportPaymentOrderDetail,
  relationAssetClassifyTrial
} from '@/api/asset.js'
import { orderOpAffairAll } from '@/api/affair'
import { getCustomizeSetting } from '@/api/customize'
import { ElMessage, ElMessageBox } from 'element-plus'
import { doPrint } from '@/utils/exportUtil.js'
import utils from '@/common/js/utils' // 公共方法
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'
import { computed } from 'vue'
const report = defineAsyncComponent(() => import('./report'))
const reportDetail = defineAsyncComponent(() => import('./reportDetail'))
const PurchOrderModify = defineAsyncComponent(() => import('./modify'))
import EleGallery from '@/components/UploadImgNew/eleGallery'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'orderId', 'id'])

const tableKey = ref(
  'assetPaymentOrderModify-com.slip.spd.entity.vo.asset.AssetPaymentOrderDetailVO'
)
const selectAssetClassifyInfo = ref({
  visible: false,
  id: '',
  saveEmpty: true,
  query: {},
})
const reportInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const reportDetailInfo = ref({
  visible: false,
  orderId: '',
})
const infoList = ref({
  data: {},
  fieldList: [
    {label: "试用科室",value: "deptName",type: "text"},
    { label: "试用开始日期", value: "trialStartDate", type: "text" },
    { label: "试用截止日期", value: "trialEndDate", type: "text" },
    { label: "设备名称", value: "assetName", type: "text" },
    { label: "规格", value: "standard", type: "text" },
    { label: "序列号", value: "sequenceNo", type: "text" },
    { label: "注册证号", value: "registerCode", type: "text" },
    { label: "生产厂家", value: "brandName", type: "text" },
    { label: "生产日期", value: "productionDate", type: "text" },
    { label: "供应商", value: "supplierName", type: "text" },
    { label: "安装日期", value: "installDate", type: "text" },
    { label: "安装地点", value: "installLocation", type: "text" },
    { label: "联系人", value: "contact", type: "text" },
    { label: "联系电话", value: "phone", type: "text" },
    { label: "附件", value: "mainFileUrlList",type: 'slot',
      className: 'not-br', },
    { label: "设备描述", value: "remark", type: "text",className: 'not-br', },
    { label: "试用方案", value: "trialPlan", type: "text",className: 'not-br', },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
    sortString: '',
    copyQueryMap: {},
    groupMap: {},
    groups: [],
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [],
  btnList: [],
})

const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 110,
    orderId: props.id || props.orderId,
    sort: 'operate_time desc',
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
  tableKey: '',
})

const canPrint = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:printDetail') &&
    infoList.value.data.status !== 1
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:excel') &&
    infoList.value.data.status !== 1
  )
})
//驳回
const canReject = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:reject') &&
    (infoList.value.data.status === 2 || infoList.value.data.status === 3) &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_trial_approval == 1
  )
})
const canCompleted = computed(() => {
  return proxy.$permission('deviceTrialManage:completed') && infoList.value.data.status === 7
})
const canReportDetails = computed(() => {
  return proxy.$permission('deviceTrialManage:reportDetails') && infoList.value.data.status === 5
})
const canRelatedAssets = computed(() => {
  return proxy.$permission('deviceTrialManage:classification') && infoList.value.data.status === 5
})
//拒绝
const canRefuse = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:refuse') &&
    (infoList.value.data.status === 2 || infoList.value.data.status === 3) &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_trial_approval == 1
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:submit') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 4)
  )
})
const canCheck = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:check') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_trial_approval == 1
  )
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:update') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 4)
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:revoke') &&
    (infoList.value.data.status === 2 ||
      (infoList.value.data.status === 7 &&
        proxy.$store.state.permission.systemConfig
          .allow_assets_trial_approval == 0))
  )
})
const canCancelAudit = computed(() => {
  return (
    proxy.$permission('deviceTrialManage:cancelAudit') &&
    infoList.value.data.status === 7 &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_trial_approval != 0
  )
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件shows
  },
})

setData()
function setData() {
  let obj = {
    
  }
  getCustomize()
}
function returnModify() {
  if (props.id || props.orderId) {
    getCustomize()
  }
}

function completed(row) {
  reportInfo.value.visible = true
  reportInfo.value.title = '试用完成'
  reportInfo.value.orderId = infoList.value.data.id
}

function reportDetails(row) {
  reportDetailInfo.value.orderId = infoList.value.data.id
  reportDetailInfo.value.visible = true
}

function relatedAssets(row) {
  selectAssetClassifyInfo.value.visible = true
  selectAssetClassifyInfo.value.id = infoList.value.data.id
}

function selectAssetClassifyInfoCallBack(row) {
  if (row && row.id) {
    let params = {
      id: infoList.value.data.id,
      assetClassifyId: row.id
    }
    relationAssetClassifyTrial(params).then(res=>{
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      getList()
    })
  }
}

//导出excel
function exportExcel() {
  exportPaymentOrderDetail(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetTrialReportDetail',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            // applicationId: infoList.value.data.id,
            orderId: props.id || props.orderId,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.value.query,
            }),
          },
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id || props.orderId,
      tempCode: 'paymentDeatil',
      orderType: 0,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id || props.orderId,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}

function getOrderInfo(orderId) {
  getTrialById(orderId).then((resp) => {
    if (resp && resp.success) {
      infoList.value['data'] = resp.data
      // infoList.data.mainFileUrlList = utils.splitArr(infoList.data.filePath)
    }
  })
}
function update() {
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改设备试用'
  // 显示信息
  modifyInfo.value.orderId = props.id || props.orderId
  modifyInfo.value.tableKey =
    'assetPaymentOrderModify-com.slip.spd.entity.vo.asset.AssetPaymentOrderDetailVO'
}
function handelMethodRequest(method) {
  const ids = getIds(infoList.value.data)
  if (
    method === 'submit' &&
    proxy.$store.state.permission.systemConfig
      .allow_assets_trial_approval == 2
  ) {
    let data = {
      flowTaskCommentDto: { approvalType: 'submit' },
      processDefinitionKey: 'assetTrial',
      orderIds: [infoList.value.data.id],
    }
    methodTrial(data, 'flowSubmit').then((resp) => {
      if (resp && resp.success) {
        getCustomize()
      }
    })
  } else if (method === 'reject') {
    proxy
      .$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '驳回理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: infoList.value.data.id,
          orderId: infoList.value.data.id,
          checkOpt: value,
        }
        methodTrial(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else if (method === 'refuse') {
    proxy
      .$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '拒绝理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: infoList.value.data.id,
          orderId: infoList.value.data.id,
          checkOpt: value,
        }
        methodTrial(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else if (method === 'stop') {
    proxy
      .$prompt('请输入中止原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.isNotEmptyString,
        inputErrorMessage: '请输入中止原因并不超过200字符',
      })
      .then(({ value }) => {
        const data = {
          ids: ids,
          stopReason: value,
        }
        methodTrial(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else if (method === 'flowApproved') {
    methodTrial({ orderIds: ids }, method).then((resp) => {
      if (resp.success) {
        getCustomize()
      }
    })
  } else {
    methodTrial(ids, method).then((resp) => {
      if (resp.success) {
        if (
          (method === 'revoke' || method === 'cancelAudit') &&
          proxy.$route.query.processInstanceId
        ) {
          proxy.$fn.setFlowPath(proxy)
          return
        }
        getCustomize()
      }
    })
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
  }
  return ids
}
function getCustomize() {
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.id || props.orderId
      getOrderInfo(props.id || props.orderId)
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
</script>
<style scoped lang="scss">
:deep(.page-table) {
  .el-table {
    overflow-y: hidden;
  }
}
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
